<?PHP
/**
 * Returns the rate of the currency for the specified date
 * if not found, returns -1
 *
 * @param string $currencyCharCode - char code of the currency: EUR, USD, RUB etc.
 * @param string $date - date for the rate dd/mm/yyyy
 * @return rate - decimal, rate if success, -1 if failure
 */
function GetRateByDate($currencyCharCode, $date)
{
	$currencyCharCode = strtoupper($currencyCharCode);
	$handle = @fopen ("http://www.cbr.ru/scripts/XML_daily.asp?date_req=".$date,'r');
	if ($handle===false) return -1; 
	$contents = '';
	do {
		$data = fread($handle, 8192);
		if (strlen($data) == 0)
		{
			break;
		}
		$contents .= $data;
	} while(true);

	//echo $contents;

	$xml = new XMLReader();
	$xml->XML($contents);
	$wait4code = false;
	$wait4valTag = false;
	$wait4value = false;
	$val = -1;
	while($xml->read())
	{
		if ($xml->nodeType == XMLReader::ELEMENT)
		{
			$name = strtoupper($xml->name);
			if ($name == 'CHARCODE')
			{
				$wait4code = true;
				continue;
			}
			elseif (($name == 'VALUE')&& $wait4valTag)
			{
				$wait4value = true;
				continue;
			}
			$wait4code = false;
		}
		elseif ($xml->nodeType == XMLReader::TEXT)
		{
			if ($wait4code)
			{
				$code = strtoupper($xml->value);
				if ($code==$currencyCharCode) {$wait4valTag = true;}
				$wait4code = false;
			}
			elseif ($wait4value)
			{
				$val = $xml->value;
				break;
			}
		}
	}
	$xml->close();
	return $val;
}
?>